Meow King March 08, 2024 Updated: March 08, 2024 #algorithm #union-find
source
算法基础课界面
solution code and explain:
#include <iostream>
using namespace std;
const int N = 50010;
int f[N], d[N];
int find(int x) {
if (x != f[x]) {
int tmp = find(f[x]); d[x] += d[f[x]]; f[x] = tmp;
}
return f[x];
}
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n, k;
cin >> n >> k;
for (int i = 1; i <= n; i ++) f[i] = i;
int wn = 0;
while (k --) {
int op, x, y;
cin >> op >> x >> y;
if (x > n || y > n) {
wn ++;
continue;
}
int rx = find(x);
int ry = find(y);
if (op == 1) {
if (rx == ry) { if ((d[x] - d[y]) % 3) wn ++;
} else {
f[rx] = ry;
d[rx] = d[y] - d[x]; }
} else if (op == 2) {
if (rx == ry) { if ((d[x] - d[y] - 1) % 3) wn ++;
} else {
f[rx] = ry;
d[rx] = d[y] - d[x] + 1;
}
} else cout << "IMPOSSIBLE";
}
cout << wn << endl;
return 0;
}